package com.lututong.uarttools;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

    private static final String TAG= "MainActivity";

    private static final int UARTDATA= 8001;
    UartJniTool  uartJniTool;
    ToggleButton readUartBtn;
    Button writeUartBtn;
    TextView uartText;
    private int offset;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        uartJniTool = new UartJniTool(mhandler);
        //uartJniTool.uartToolStart();

        uartText = (TextView)findViewById(R.id.uartText);
        uartText.setMovementMethod(ScrollingMovementMethod.getInstance());

        readUartBtn = (ToggleButton)findViewById(R.id.readUartBtn);
        writeUartBtn = (Button)findViewById(R.id.writeUartBtn);

        readUartBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (readUartBtn.isChecked()){
                   int result = uartJniTool.uartToolStart();
                    if (result < 0){
                        readUartBtn.setChecked(false);
                    }
                }else {
                    uartJniTool.uartToolStop();
                }
            }
        });

        writeUartBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uartJniTool.writeUartData();
            }
        });
    }

    Handler mhandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UARTDATA:
                    int uartData = msg.getData().getInt("UARTDATA");
                    Log.i(TAG, "handleMessage---->"+uartData);
                    uartText.append(numToHex8(uartData)+" ");
                    offset=uartText.getLineCount()*uartText.getLineHeight();
                    if(offset>uartText.getHeight()){
                        uartText.scrollTo(0,offset-uartText.getHeight());
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public static String numToHex8(int b) {
        return String.format("0x%02x", b);//2表示需要两个16进行数
    }
}
